package com.ruoyi.common.minio.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.ruoyi.common.minio.properties.MinioProperties;
import io.minio.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Slf4j
public class MinioUtils {
    private MinioClient minioClient;
    private MinioProperties properties;
    public String uploadFile(String filePath){
        File file = new File(filePath);
        String path = this.uploadFile(file);
        return path;
    }
    public String uploadFileByMultipartFile(MultipartFile file){
        // 创建临时文件
        try {
            String prefix = UUID.randomUUID().toString();
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File tempFile = File.createTempFile(prefix, suffix);
            file.transferTo(tempFile);
            String path = uploadFile(tempFile);
            tempFile.deleteOnExit();
            return path;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("临时文件创建失败");
        }
    }
    public String uploadFile(MultipartFile file){
        try{
            // 检查桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
            if (!found) {
                // 创建新桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
                log.info("Bucket "+ properties.getBucketName() +" created successfully.");
            } else {
                log.info("Bucket "+ properties.getBucketName() +" already exists.");
            }
            String fileName = "";
            if (file.getName() != null) {
                fileName = DigestUtil.md5Hex(file.getInputStream()) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }else {
                fileName = DigestUtil.md5Hex(file.getInputStream());
            }
            // 上传文件
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(properties.getBucketName())
                    .object(properties.getFileFolder() + "/" + fileName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), file.getSize())
                    .build());

            log.info(file.getOriginalFilename() + "上传成功");
            return properties.getEndPoint() + "/" + properties.getBucketName() + "/" + properties.getFileFolder() + "/" + fileName;
        }
        catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("文件上传出错");
        }
    }
    public String uploadFile(File file){
        try{
            // 检查桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
            if (!found) {
                // 创建新桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
                log.info("Bucket "+ properties.getBucketName() +" created successfully.");
            } else {
                log.info("Bucket "+ properties.getBucketName() +" already exists.");
            }
            String fileName = "";
            if (file.getName() != null) {
                fileName = DigestUtil.md5Hex(file) + file.getName().substring(file.getName().lastIndexOf("."));
            }else {
                fileName = DigestUtil.md5Hex(file);
            }
            // 上传文件
            minioClient.uploadObject(
                UploadObjectArgs.builder()
                    .bucket(properties.getBucketName())
                    .object(properties.getFileFolder() + "/" + fileName)
                    .filename(file.getAbsolutePath()) // 修正文件路径
                    .build());

            log.info(file.getName() + "上传成功");
            return properties.getEndPoint() + "/" + properties.getBucketName() + "/" + properties.getFileFolder() + "/" + fileName;
        }
        catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("文件上传出错");
        }
    }
}
